using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using secret_server.Models;
using Microsoft.Extensions.Logging;

namespace secret_server.Data
{
    public class ApplicationSeed
    {
        public static async void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new ApplicationDbContext(serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
            {
                if (context.Users.Any(u => u.UserName == "zicjin@gmail.com"))
                {
                    return;
                }

                // https://stackoverflow.com/a/34791867
                string[] roles = new string[] { "Admin", "Creator", "Viewer" };
                foreach (string role in roles)
                {
                    var roleStore = new RoleStore<IdentityRole>(context);
                    if (!context.Roles.Any(r => r.Name == role))
                    {
                        await roleStore.CreateAsync(new IdentityRole { Name = role, NormalizedName = role });
                        // await roleStore.CreateAsync(new IdentityRole(role)); // has bug
                    }
                }

                var user = new ServerUser
                {
                    // asp.net core issus: Email & UserName must be same
                    Email = "zicjin@gmail.com",
                    NormalizedEmail = "ZICJIN@GMAIL.COM",
                    UserName = "zicjin@gmail.com",
                    NormalizedUserName = "ZICJIN@GMAIL.COM",
                    EmailConfirmed = true,
                    SecurityStamp = Guid.NewGuid().ToString("D")
                };

                var password = new PasswordHasher<ServerUser>();
                user.PasswordHash = password.HashPassword(user, "Z565656z#");

                var userStore = new UserStore<ServerUser>(context);
                var result = await userStore.CreateAsync(user);
                if (result.Succeeded) {
                    await userStore.AddToRoleAsync(user, "Admin");
                }

                await context.SaveChangesAsync();
            }
        }
    }
}
